package com.scors.logos.jpa.impl;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.scors.logos.jpa.IUserDao;
import com.scors.logos.model.User;

@Transactional
@Repository("userDao")
public class UserDaoImpl extends PersistenceJPAGenericImpl<User> implements
	IUserDao {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public UserDaoImpl() {
	super(User.class);
	// TODO Auto-generated constructor stub
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User findByFullname(String fullname) {
	log.debug("getting UserImpl instance with fullname: " + fullname);
	try {
	    Query query = entityManager
		    .createQuery("select u from User u where u.fullname like :fullname");
	    query.setParameter("fullname", fullname);
	    User user = (User) query.getSingleResult();
	    log.debug("findByFullname successful");
	    return user;
	} catch (RuntimeException re) {
	    log.error("findByFullname failed", re);
	    return null;
	}
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User findByLogin(String login) {
	log.debug("getting UserImpl instance with login: " + login);
	try {
	    Query query = entityManager
		    .createQuery("select u from User u where u.login like :login");
	    query.setParameter("login", login);
	    User user = (User) query.getSingleResult();
	    log.debug("findByLogin successful");
	    return user;
	} catch (RuntimeException re) {
	    log.error("findByLogin failed", re);
	    return null;
	}
    }

    @Override
    public String findFriendByLogin(String login) {
	log.debug("getting UserImpl instance with login: " + login);
	try {
	    Query query = entityManager
		    .createQuery("select u from User u where u.login like :login");
	    query.setParameter("login", login);
	    User user = (User) query.getSingleResult();
	    log.debug("findFriendByLogin successful");
	    String listAmiOn = "";
	    for (User user2 : user.getFriends()) {
		listAmiOn += user2.getName();
	    }
	    return listAmiOn;
	} catch (RuntimeException re) {
	    log.error("findFriendByLogin failed", re);
	    return null;
	}
    }

}
